package cn.kgm.config;

import cn.kgm.pojo.Configuration;
import cn.kgm.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 专门解析映射配置文件的对象
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        // 获取根节点
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> sqls = rootElement.selectNodes("//select");
        for (Element sql : sqls) {
            String id = sql.attributeValue("id");
            String resultType = sql.attributeValue("resultType");
            String parameterType = sql.attributeValue("parameterType");
            String sqlStr = sql.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setStatementId(namespace.concat(".").concat(id));
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlStr);
            mappedStatement.setSqlCommandType("select");

            this.configuration.put(mappedStatement.getStatementId(), mappedStatement);
        }
    }
}
